<template>
	<a-modal :centered="true" open title="报警配置" width="660px" height="770px" @cancel="CloseModal">
		<div class="alarm-configuration">
			<div class="the-common-title">
				<div>
					<global-svg-icon icon-name="config-title-tri" width="3px" height="18px" style="margin-right: 16px; cursor: pointer" />
					报警配置
				</div>
				<div class="clear" @click="ClearConfiguration">清空配置</div>
			</div>
			<a-collapse v-model:activeKey="activeKey" :bordered="false" style="background: rgba(255, 255, 255, 0)">
				<template #expandIcon="{ isActive }">
					<CaretRightOutlined :rotate="isActive ? 90 : 0" :style="{ color: '#B0B5C0' }" />
				</template>
				<a-collapse-panel key="1" header="存储空间" :style="customStyle">
					<a-form ref="formRef" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
						<a-form-item label="存储空间使用占比阈值" name="memoryThreshold" :rules="[{ required: true, message: '请输入0-100的数字' }]">
							<a-input-number
								v-model:value.trim="formState.memoryThreshold"
								:min="0"
								:max="100"
								:precision="0"
								placeholder="请输入0-100的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> %</span>
						</a-form-item>
						<a-form-item label="报警时间间隔" name="memoryInterval" :rules="[{ required: true, message: '请输入1-99999的数字' }]">
							<a-input-number
								v-model:value.trim="formState.memoryInterval"
								:min="1"
								:max="99999"
								:precision="0"
								placeholder="请输入1-99999的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> min</span>
						</a-form-item>
					</a-form>
					<template #extra>
						<div @click="changeMemorySpace">
							<a-switch v-model:checked="formCheckbox.memorySpace" />
						</div>
					</template>
				</a-collapse-panel>
				<a-collapse-panel key="2" header="CPU利用率" :style="customStyle">
					<a-form ref="cpuFormRef" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
						<a-form-item label="CPU利用率阈值" name="cpuThreshold" :rules="[{ required: true, message: '请输入0-100的数字' }]">
							<a-input-number
								v-model:value.trim="formState.cpuThreshold"
								:min="0"
								:max="100"
								:precision="0"
								placeholder="请输入0-100的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> %</span>
						</a-form-item>
						<a-form-item label="报警时间间隔" name="cpuInterval" :rules="[{ required: true, message: '请输入1-99999的数字' }]">
							<a-input-number
								v-model:value.trim="formState.cpuInterval"
								:min="1"
								:max="99999"
								:precision="0"
								placeholder="请输入1-99999的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> min</span>
						</a-form-item>
						<a-form-item label="报警延迟" name="cpuDelay" :rules="[{ validator: delay, required: true, message: '请输入5的整数倍的数字' }]">
							<a-input-number
								v-model:value.trim="formState.cpuDelay"
								:min="1"
								:max="3600"
								:precision="0"
								placeholder="请输入5的整数倍的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> s</span>
						</a-form-item>
					</a-form>
					<template #extra>
						<div @click="changeCpu">
							<a-switch v-model:checked="formCheckbox.cpu" />
						</div>
					</template>
				</a-collapse-panel>
				<a-collapse-panel key="3" header="NPU利用率" :style="customStyle">
					<a-form ref="npuFormRef" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
						<a-form-item label="NPU利用率阈值" name="npuThreshold" :rules="[{ required: true, message: '请输入0-100的数字' }]">
							<a-input-number
								v-model:value.trim="formState.npuThreshold"
								:min="0"
								:max="100"
								:precision="0"
								placeholder="请输入0-100的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> %</span>
						</a-form-item>
						<a-form-item label="报警时间间隔" name="npuInterval" :rules="[{ required: true, message: '请输入1-99999的数字' }]">
							<a-input-number
								v-model:value.trim="formState.npuInterval"
								:min="1"
								:max="99999"
								:precision="0"
								placeholder="请输入1-99999的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> min</span>
						</a-form-item>
						<a-form-item label="报警延迟" name="npuDelay" :rules="[{ validator: delay, required: true, message: '请输入5的整数倍的数字' }]">
							<a-input-number
								v-model:value.trim="formState.npuDelay"
								:min="1"
								:max="3600"
								:precision="0"
								placeholder="请输入5的整数倍的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> s</span>
						</a-form-item>
					</a-form>
					<template #extra>
						<div @click="changeNpu">
							<a-switch v-model:checked="formCheckbox.npu" />
						</div>
					</template>
				</a-collapse-panel>
				<a-collapse-panel key="4" header="内存利用率" :style="customStyle">
					<a-form ref="storageFormRef" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
						<a-form-item label="内存利用率阈值" name="storageThreshold" :rules="[{ required: true, message: '请输入0-100的数字' }]">
							<a-input-number
								v-model:value.trim="formState.storageThreshold"
								:min="0"
								:max="100"
								:precision="0"
								placeholder="请输入0-100的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> %</span>
						</a-form-item>
						<a-form-item label="报警时间间隔" name="storageInterval" :rules="[{ required: true, message: '请输入1-99999的数字' }]">
							<a-input-number
								v-model:value.trim="formState.storageInterval"
								:min="1"
								:max="99999"
								:precision="0"
								placeholder="请输入1-99999的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> min</span>
						</a-form-item>
						<a-form-item
							label="报警延迟"
							name="storageDelay"
							:rules="[{ validator: delay, required: true, message: '请输入5的整数倍的数字' }]"
						>
							<a-input-number
								v-model:value.trim="formState.storageDelay"
								:min="1"
								:max="3600"
								:precision="0"
								placeholder="请输入5的整数倍的数字"
							/>
							<span style="line-height: 36px; color: #8b949e"> s</span>
						</a-form-item>
					</a-form>
					<template #extra>
						<div @click="changeStorage">
							<a-switch v-model:checked="formCheckbox.storage" />
						</div>
					</template>
				</a-collapse-panel>
			</a-collapse>
		</div>
		<template #footer>
			<a-button size="small" class="btn-default" @click="CloseModal">取消</a-button>
			<a-button size="small" class="btn-default" :loading="copyLoading" @click="FormSave('copy')">复制到...</a-button>
			<a-button size="small" type="primary" :loading="loading" @click="FormSave('submit')">确定</a-button>
		</template>
		<!-- 选择升级设备 -->
		<a-modal
			v-if="chooseDeviceVisible"
			:centered="true"
			class="choose-device-configuration"
			:open="chooseDeviceVisible"
			:body-style="{ padding: '40px 32px' }"
			width="600px"
			ok-text="确定"
			title="复制配置信息到..."
			:confirm-loading="confirmLoading"
			@cancel="closeDeviceUpdate"
			@ok="FormSave('submitDevice')"
		>
			<div class="table-box">
				<a-table
					ref="tableRef"
					:data-source="dialogSataSource"
					:row-selection="rowSelection"
					:destroy-on-close="true"
					:row-key="rowKey"
					size="small"
					:scroll="{ y: 266, x: 510 }"
					:columns="updateColumns"
					:pagination="false"
				>
					<template #bodyCell="{ column, text }">
						<template v-if="column.dataIndex === 'configFlag'">{{ text.configFlag === 0 ? '无' : '有' }}</template>
					</template>
				</a-table>
			</div>
		</a-modal>
	</a-modal>
</template>

<script setup lang="ts" name="AlarmConfiguration">
import { CaretRightOutlined } from '@ant-design/icons-vue';
import { ref } from 'vue';
import { useDeleteModal } from '@/global-hooks/base.hooks';
import { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { BoxManageApi } from '../../../api';

const props = withDefaults(defineProps<{ serial: string }>(), {
	serial: 'a'
});

const emits = defineEmits<{
	(e: 'ok'): void;
	(e: 'close'): void;
}>();

const { setOpenDeleteModal } = useDeleteModal();

const $message: any = inject('$message');

const formRef = ref<FormInstance>();
const cpuFormRef = ref<FormInstance>();
const npuFormRef = ref<FormInstance>();
const storageFormRef = ref<FormInstance>();
const activeKey = ref(['0']);
const customStyle = 'background: #161F31;border-radius: 6px;margin-bottom: 16px;border: 1px solid #2B3A50;font-size:16px;font-weight:700';
const copyLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
interface FormState {
	boxSerialList?: any[];
	operateFlag?: number;
	memorySpace?: boolean | number;
	memoryThreshold?: number;
	memoryInterval?: number;
	cpu?: boolean | number;
	cpuThreshold?: number;
	cpuInterval?: number;
	cpuDelay?: number;
	npu?: boolean | number;
	npuThreshold?: number;
	npuInterval?: number;
	npuDelay?: number;
	storage?: boolean | number;
	storageThreshold?: number;
	storageInterval?: number;
	storageDelay?: number;
}
const formState = ref<FormState>({
	boxSerialList: [],
	operateFlag: 0, // 0 - 新增/修改，1 - 删除
	memorySpace: false,
	cpu: false,
	npu: false,
	storage: false
});
const formCheckbox = ref<FormState>({
	memorySpace: false,
	cpu: false,
	npu: false,
	storage: false
});
// 盒子列表弹框
const chooseDeviceVisible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
// 弹窗表格体
const tableRef = ref();
// 弹窗内容
const rowKey = ref<string>('boxSerial');
const dialogSataSource = ref<Record<string, string>[]>([]);
const upBoxDeviceRows = ref<Record<string, string>[]>([]);
const updateColumns: TsGlobalType.TsTableColumn[] = [
	{ dataIndex: 'boxName', title: '盒子名称', width: 120, ellipsis: true },
	{ dataIndex: 'boxSerial', title: 'SN码', width: 226, ellipsis: true },
	{ dataIndex: 'configFlag', title: '报警配置', custom: true, width: 120, ellipsis: true }
];
// 清除
const ClearConfiguration = (): void => {
	const modalInfo = { title: '确认清空当前配置？', okText: '确认', cancelText: '取消' };
	const confirmFun = (): void => {
		activeKey.value = ['0'];
		formRef.value?.resetFields();
		cpuFormRef.value?.resetFields();
		npuFormRef.value?.resetFields();
		storageFormRef.value?.resetFields();
		let params = {
			boxSerialList: formState.value.boxSerialList,
			operateFlag: 1,
			memorySpace: false,
			cpu: false,
			npu: false,
			storage: false
		};
		formState.value = params;
		formCheckbox.value = params;
	};

	setOpenDeleteModal(confirmFun, modalInfo);
};
// 点击开关
const changeMemorySpace = (event: MouseEvent): void => {
	if (formCheckbox.value.memorySpace) {
		console.log(1);
		formState.value.memorySpace = true;
		// 如果已经展开则不添加key
		if (!activeKey.value.includes('1')) {
			activeKey.value.push('1');
		}
	} else {
		activeKey.value = activeKey.value.filter((item: string) => item !== '1');
		formRef.value?.clearValidate();
	}
	event.stopPropagation();
};
const changeCpu = (event: MouseEvent): void => {
	if (formCheckbox.value.cpu) {
		formState.value.cpu = true;
		// 如果已经展开则不添加key
		if (!activeKey.value.includes('2')) {
			activeKey.value.push('2');
		}
	} else {
		activeKey.value = activeKey.value.filter((item: string) => item !== '2');
		cpuFormRef.value?.clearValidate();
	}
	event.stopPropagation();
};
const changeNpu = (event: MouseEvent): void => {
	if (formCheckbox.value.npu) {
		formState.value.npu = true;
		// 如果已经展开则不添加key
		if (!activeKey.value.includes('3')) {
			activeKey.value.push('3');
		}
	} else {
		activeKey.value = activeKey.value.filter((item: string) => item !== '3');
		npuFormRef.value?.clearValidate();
	}
	event.stopPropagation();
};
const changeStorage = (event: MouseEvent): void => {
	if (formCheckbox.value.storage) {
		formState.value.storage = true;
		// 如果已经展开则不添加key
		if (!activeKey.value.includes('4')) {
			activeKey.value.push('4');
		}
	} else {
		activeKey.value = activeKey.value.filter((item: string) => item !== '4');
		storageFormRef.value?.clearValidate();
	}
	event.stopPropagation();
};
// 判断是否是5的正整数
const delay = async (_rule: Rule, value: number): Promise<void> => {
	if (!value) {
		return Promise.reject('请输入5的整数倍的数字');
	} else if (value % 5 !== 0) {
		return Promise.reject('请输入5的整数倍的数字');
	}
	return Promise.resolve();
};
const getAlarmConfiguration = async (): Promise<void> => {
	try {
		let res: TsRes = await BoxManageApi.getByBoxSerial(props.serial);
		if (res.code === 0) {
			if (res.data) {
				if (res.data.memorySpace === 1) {
					activeKey.value.push(res.data.memorySpace.toString());
					res.data.memorySpace = true;
					formCheckbox.value.memorySpace = true;
				} else {
					res.data.memorySpace = false;
				}
				if (res.data.cpu === 2) {
					activeKey.value.push(res.data.cpu.toString());
					res.data.cpu = true;
					formCheckbox.value.cpu = true;
				} else {
					res.data.cpu = false;
				}
				if (res.data.npu === 3) {
					activeKey.value.push(res.data.npu.toString());
					res.data.npu = true;
					formCheckbox.value.npu = true;
				} else {
					res.data.npu = false;
				}
				if (res.data.storage === 4) {
					activeKey.value.push(res.data.storage.toString());
					res.data.storage = true;
					formCheckbox.value.storage = true;
				} else {
					res.data.storage = false;
				}
				formState.value = res.data;
			}
			formState.value.operateFlag = 0;
			formState.value.boxSerialList = [props.serial];
		}
	} catch (error) {
		console.log('error', error);
	}
};
// 开启弹框
const showBoxesVisible = async (): Promise<void> => {
	chooseDeviceVisible.value = true;
	try {
		let res: TsRes = await BoxManageApi.getBoxHardwareConf();
		res.data.map((item: any, i: number) => {
			if (item.boxSerial === props.serial) {
				res.data.splice(i, 1);
			}
		});
		dialogSataSource.value = res.data;
	} catch (error) {
		console.log('error', error);
	}
};

// 关闭弹窗
const closeDeviceUpdate = (): void => {
	chooseDeviceVisible.value = false;
};
// 多选
// rowkeys类型
declare type Key = string | number;
const rowSelection = {
	onChange: (selectedRowKeys: Key[], selectedRows: Key[]) => {
		upBoxDeviceRows.value = selectedRows.map((item: any) => item.boxSerial);
	}
};
const formSubmit = (data: any, type: string): void => {
	let params = formState.value;
	if (formCheckbox.value.memorySpace) {
		params.memorySpace = 1;
	} else {
		delete params.memorySpace;
		delete params.memoryThreshold;
		delete params.memoryInterval;
	}
	if (formCheckbox.value.cpu) {
		params.cpu = 2;
	} else {
		delete params.cpu;
		delete params.cpuThreshold;
		delete params.cpuInterval;
		delete params.cpuDelay;
	}
	if (formCheckbox.value.npu) {
		params.npu = 3;
	} else {
		delete params.npu;
		delete params.npuThreshold;
		delete params.npuInterval;
		delete params.npuDelay;
	}
	if (formCheckbox.value.storage) {
		params.storage = 4;
	} else {
		delete params.storage;
		delete params.storageThreshold;
		delete params.storageInterval;
		delete params.storageDelay;
	}
	// 如果都是false的话操作为1，删除
	if (!params.storage && !params.memorySpace && !params.cpu && !params.npu) {
		params.operateFlag = 1;
	}
	if (type !== 'copy') {
		if (type === 'submitDevice') {
			confirmLoading.value = true;
			if (upBoxDeviceRows.value.length === 0) {
				$message.warning('请选中设备！');
				confirmLoading.value = false;
				return;
			}
			params.boxSerialList = params.boxSerialList?.concat(upBoxDeviceRows.value);
		} else {
			loading.value = true;
		}
	} else {
		copyLoading.value = true;
	}
	setTimeout(async () => {
		if (!data.includes(false)) {
			if (type === 'copy') {
				await showBoxesVisible();
				copyLoading.value = false;
			} else {
				try {
					let res: TsRes = await BoxManageApi.saveOrUpdateBatch(params);
					if (res.code === 0) {
						confirmLoading.value = false;
						loading.value = false;
						$message.success('保存成功');
						closeDeviceUpdate();
						emits('close');
					}
				} catch (error) {
					confirmLoading.value = false;
					loading.value = false;
				}
			}
		} else {
			copyLoading.value = false;
		}
	}, 2000);
};
const FormSave = async (type: string): Promise<void> => {
	let arr: any[] = [];
	if (formCheckbox.value.memorySpace) {
		formRef.value
			?.validate()
			.then(async (): Promise<any> => {
				try {
					arr.push(true);
				} catch (error) {
					// eslint-disable-next-line promise/always-return
				} finally {
					//
				}
			})
			.catch((error: any) => {
				activeKey.value.push('1');
				formRef.value?.scrollToField(error.errorFields[0].name);
				arr.push(false);
				confirmLoading.value = false;
				loading.value = false;
				console.log('表单提交验证错误', error);
			});
	}
	if (formCheckbox.value.cpu) {
		cpuFormRef.value
			?.validate()
			.then((): any => {
				try {
					arr.push(true);
				} catch (error) {
					// eslint-disable-next-line promise/always-return
				} finally {
					//
				}
			})
			.catch((error: any) => {
				activeKey.value.push('2');
				if (!arr.includes(false)) {
					formRef.value?.scrollToField(error.errorFields[0].name);
				}
				arr.push(false);
				confirmLoading.value = false;
				loading.value = false;
				console.log('表单提交验证错误', error);
			});
	}
	if (formCheckbox.value.npu) {
		npuFormRef.value
			?.validate()
			.then((): any => {
				try {
					arr.push(true);
				} catch (error) {
					// eslint-disable-next-line promise/always-return
				} finally {
					//
				}
			})
			.catch((error: any) => {
				activeKey.value.push('3');
				if (!arr.includes(false)) {
					npuFormRef.value?.scrollToField(error.errorFields[0].name);
				}
				arr.push(false);
				confirmLoading.value = false;
				loading.value = false;
				console.log('表单提交验证错误', error);
			});
	}
	if (formCheckbox.value.storage) {
		storageFormRef.value
			?.validate()
			.then((): any => {
				try {
					arr.push(true);
				} catch (error) {
					// eslint-disable-next-line promise/always-return
				} finally {
					//
				}
			})
			.catch((error: any) => {
				activeKey.value.push('4');
				if (!arr.includes(false)) {
					storageFormRef.value?.scrollToField(error.errorFields[0].name);
				}
				arr.push(false);
				confirmLoading.value = false;
				loading.value = false;
				console.log('表单提交验证错误', activeKey);
			});
	}
	if (type === 'submitDevice') {
		await formSubmit(arr, type);
	} else {
		await formSubmit(arr, type);
	}
};

const CloseModal = (): void => {
	emits('close');
};

onMounted(async () => {
	await getAlarmConfiguration();
});
</script>

<style lang="less" scoped>
@import url('../../../style.less');
</style>
